﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using SmartMap.Domain;
using System.Web.Script.Serialization;
using SmartMap.Domain.Handlers;
using System.Web.SessionState;

namespace SmartMap.service
{
	public class cService : IHttpHandler, IRequiresSessionState
	{

		public bool IsReusable
		{
			get
			{
				return true;
			}
		}

		public void ProcessRequest(HttpContext context)
		{
			// Gets the action based on request
			SmartMapBaseHandler handler = SmartMapBaseHandler.GetHandler();

			try
			{
				if (handler != null)
				{

					handler.Execute();
					string output = handler.Output;
					context.Response.ContentType = "application/x-javascript";
					context.Response.Write(output);
				}
				else
				{
					context.Response.StatusCode = 404;
				}
			}
			catch (Exception e)
			{
				SmartMapException ajaxEx = new SmartMapException();
				if (e.InnerException != null)
				{
					ajaxEx.InnerExceptionStackTrace = e.InnerException.StackTrace;
					ajaxEx.InnerExceptionMessage = e.InnerException.Message;
				}
				else
				{
					ajaxEx.InnerExceptionStackTrace = "";
					ajaxEx.InnerExceptionMessage = "";
				}
				ajaxEx.Message = e.Message;
				ajaxEx.StackTrace = e.StackTrace;


				string error = new JavaScriptSerializer().Serialize(ajaxEx);
				context.Response.ContentType = "application/x-javascript";
				context.Response.Write(error);
			}
			finally
			{
				if (handler != null)
				{
					handler.Dispose();
				}
			}
		}
	}
}
